import 'package:get/get.dart';
import 'package:intl/intl.dart';
import 'package:flutter/material.dart';
import 'dart:async';
import 'package:get/get.dart' hide SnackPosition;

import '../../common/index.dart';
import '../../common/model/categoryModel.dart';

class HomeController extends GetxController with GetTickerProviderStateMixin {
  final PostService post_service = PostService();
  HomeController();

  // 当前选中的日期
  DateTime selected_day = DateTime.now();
  // 当前聚焦的日期
  DateTime focused_day = DateTime.now();
  // 当前用户
  UserModel? get user => UserService().get_now_user();
  final isWatering = false.obs;

  // 动画控制器
  late AnimationController fade_controller;
  late AnimationController slide_controller;
  late AnimationController water_controller;
  late AnimationController pulse_controller;
  late AnimationController shake_controller;

  // 动画对象
  late Animation<double> fade_animation;
  late Animation<Offset> slide_animation;
  late Animation<double> pulse_animation;
  late Animation<double> water_scale_animation;
  late Animation<double> button_scale_animation;

  // 简单状态
  bool is_animating = false;
  bool show_water_drop = false;

  // 其他交互相关变量
  final RxDouble scroll_offset = 0.0.obs;
  final RxDouble view_all_scale = 1.0.obs;
  final RxDouble read_more_scale = 1.0.obs;
  final Map<int, RxDouble> category_scales = <int, RxDouble>{};
  final Map<String, RxDouble> plant_scales = <String, RxDouble>{};

  // 植物分类列表
  final List<CategoryModel> categories = [
    CategoryModel(
      category_id: '1',
      name: 'Indoor',
      image_url: 'assets/images/category_indoor.png',
    ),
    CategoryModel(
      category_id: '2',
      name: 'Outdoor',
      image_url: 'assets/images/category_outdoor.png',
    ),
    CategoryModel(
      category_id: '3',
      name: 'Flowering',
      image_url: 'assets/images/category_flowering.png',
    ),
    CategoryModel(
      category_id: '4',
      name: 'Succulents',
      image_url: 'assets/images/category_succulents.png',
    ),
  ];

  // 植物列表
  final List<PlantModel> plants = [
    PlantModel(
      id: '1',
      name: 'Monstera',
      species: 'Monstera deliciosa',
      image_url: 'assets/images/plant1.jpg',
      water_frequency: 'Every 7 days',
    ),
    PlantModel(
      id: '2',
      name: 'Snake Plant',
      species: 'Sansevieria trifasciata',
      image_url: 'assets/images/plant2.jpg',
      water_frequency: 'Every 14 days',
    ),
    PlantModel(
      id: '3',
      name: 'Peace Lily',
      species: 'Spathiphyllum',
      image_url: 'assets/images/plant3.jpg',
      water_frequency: 'Every 5 days',
    ),
  ];

  // 执行脉冲动画
  void play_pulse_animation() {
    pulse_controller.reset();
    pulse_controller.forward();
  }

  // 执行按钮点击动画
  void play_button_animation() {
    shake_controller.reset();
    shake_controller.forward();
  }

  // 执行震动动画
  void play_shake_animation() {
    shake_controller.reset();
    shake_controller.forward();
  }

  // 执行浇水动画
  void play_water_animation() {
    show_water_drop = true;
    water_controller.reset();
    water_controller.forward().then((_) {
      Timer(Duration(milliseconds: 300), () {
        show_water_drop = false;
        update(["water_animation"]);
      });
    });
    update(["water_animation"]);
  }

  // 滚动位置更新
  void updateScrollOffset(double offset) {
    scroll_offset.value = offset;
  }

  // 设置ViewAll缩放
  void setViewAllScale(double scale) {
    view_all_scale.value = scale;
  }

  // 设置ReadMore缩放
  void setReadMoreScale(double scale) {
    read_more_scale.value = scale;
  }

  // 设置分类项缩放
  void setCategoryTapScale(int index, double scale) {
    category_scales[index]?.value = scale;
  }

  // 获取分类项缩放值
  double getCategoryScale(int index) {
    return category_scales[index]?.value ?? 1.0;
  }

  // 设置植物项缩放
  void setPlantTapScale(String id, double scale) {
    plant_scales[id]?.value = scale;
  }

  // 获取植物项缩放值
  double getPlantScale(String id) {
    return plant_scales[id]?.value ?? 1.0;
  }

  // 初始化交互状态
  void _initInteractions() {
    // 初始化分类缩放值
    for (int i = 0; i < categories.length; i++) {
      category_scales[i] = 1.0.obs;
    }

    // 初始化植物缩放值
    for (var plant in plants) {
      plant_scales[plant.id] = 1.0.obs;
    }
  }

  // 获取格式化后的日期字符串
  String get formattedSelectedDay =>
      DateFormat('yyyy-MM-dd').format(selected_day);

  // 判断选中的日期是否可以浇水
  bool get canWaterToday {
    final now = DateTime.now();
    final today = DateTime(now.year, now.month, now.day);
    final selected = DateTime(
      selected_day.year,
      selected_day.month,
      selected_day.day,
    );
    return selected.isBefore(today) || selected.isAtSameMomentAs(today);
  }

  // 判断选中的日期是否已经浇水
  bool get is_watered_today {
    final water_list = user?.water_lists;
    if (water_list == null) return false;
    return water_list.contains(formattedSelectedDay);
  }

  _init_data() {
    // 初始化交互状态
    _initInteractions();

    // 播放初始页面动画
    fade_controller.forward();
    slide_controller.forward();

    update(["home"]);
  }

  void onTap() {
    play_button_animation();
  }

  // 更新选中的日期
  void updateSelectedDay(DateTime select_day, DateTime focus_day) {
    selected_day = select_day;
    focused_day = focus_day;
    play_pulse_animation();
    update(['calendar']);
  }

  void handle_watering() {
    final isLogin = Storage().get_bool(Constants.login_status);
    if (!isLogin) {
      // 提示用户登录
      SmartDialogHelper.show_snackbar(
        title: 'Prompt',
        message: 'Please login first',
      );
      RouteUtil.push(RouteNames.login);
      return;
    }

    if (!canWaterToday) {
      play_shake_animation();
      SmartDialogHelper.show_snackbar(
        title: 'Cannot Water',
        message: 'You cannot water plants on future dates.',
      );
      return;
    }

    if (is_watered_today) {
      play_shake_animation();
      SmartDialogHelper.show_snackbar(
        title: 'Already Watered',
        message:
            'This plant has already been watered on ${formattedSelectedDay}.',
      );
      return;
    }

    // 播放浇水动画
    play_water_animation();

    Future.delayed(Duration(milliseconds: 500), () {
      isWatering.value = true;

      // 创建新的waterList
      List<String> newWaterList = List<String>.from(user?.water_lists ?? []);
      newWaterList.add(formattedSelectedDay);

      // 创建新的UserModel实例
      UserModel updated_user = UserModel(
        id: user?.id,
        name: user?.name,
        password: user?.password,
        avatar_image: user?.avatar_image,
        is_vip: user?.is_vip,
        plant_list: user?.plant_list,
        water_lists: newWaterList,
      );

      // 更新用户数据
      UserService().set_user(updated_user);
      UserService().user.refresh();

      print("浇水了：${updated_user.water_lists}");
      update(["home"]);

      // 浇水完成后延迟重置状态
      Timer(Duration(milliseconds: 1500), () {
        isWatering.value = false;
        play_pulse_animation();
      });
    });
  }

  @override
  void onInit() {
    super.onInit();

    // 初始化渐变动画控制器
    fade_controller = AnimationController(
      vsync: this,
      duration: const Duration(milliseconds: 800),
    );

    // 初始化滑动动画控制器
    slide_controller = AnimationController(
      vsync: this,
      duration: const Duration(milliseconds: 600),
    );

    // 初始化浇水动画控制器
    water_controller = AnimationController(
      vsync: this,
      duration: const Duration(milliseconds: 1500),
    );

    // 初始化脉冲动画控制器
    pulse_controller = AnimationController(
      vsync: this,
      duration: const Duration(milliseconds: 400),
    );

    // 初始化震动动画控制器
    shake_controller = AnimationController(
      vsync: this,
      duration: const Duration(milliseconds: 500),
    );

    // 设置渐变动画
    fade_animation = Tween<double>(
      begin: 0.0,
      end: 1.0,
    ).animate(CurvedAnimation(parent: fade_controller, curve: Curves.easeIn));

    // 设置滑动动画
    slide_animation = Tween<Offset>(begin: Offset(0, 0.2), end: Offset.zero)
        .animate(
          CurvedAnimation(parent: slide_controller, curve: Curves.easeOutQuad),
        );

    // 设置脉冲动画
    pulse_animation = TweenSequence<double>([
      TweenSequenceItem(
        tween: Tween<double>(
          begin: 1.0,
          end: 1.15,
        ).chain(CurveTween(curve: Curves.easeInOut)),
        weight: 50,
      ),
      TweenSequenceItem(
        tween: Tween<double>(
          begin: 1.15,
          end: 1.0,
        ).chain(CurveTween(curve: Curves.easeInOut)),
        weight: 50,
      ),
    ]).animate(pulse_controller);

    // 设置水滴动画
    water_scale_animation = TweenSequence<double>([
      TweenSequenceItem(
        tween: Tween<double>(
          begin: 0.0,
          end: 1.0,
        ).chain(CurveTween(curve: Curves.easeOutBack)),
        weight: 30,
      ),
      TweenSequenceItem(
        tween: Tween<double>(
          begin: 1.0,
          end: 1.0,
        ).chain(CurveTween(curve: Curves.linear)),
        weight: 40,
      ),
      TweenSequenceItem(
        tween: Tween<double>(
          begin: 1.0,
          end: 0.0,
        ).chain(CurveTween(curve: Curves.easeIn)),
        weight: 30,
      ),
    ]).animate(water_controller);

    // 设置按钮缩放动画
    button_scale_animation = Tween<double>(begin: 1.0, end: 0.95).animate(
      CurvedAnimation(
        parent: shake_controller,
        curve: Interval(0.0, 0.3, curve: Curves.easeInOut),
      ),
    );
  }

  @override
  void onReady() {
    super.onReady();
    _init_data();
  }

  @override
  void onClose() {
    // 释放所有动画控制器
    fade_controller.dispose();
    slide_controller.dispose();
    water_controller.dispose();
    pulse_controller.dispose();
    shake_controller.dispose();
    super.onClose();
  }

  // 加载所有帖子
  Future<List<PostModel>> load_posts() async {
    try {
      // 显示加载动画
      is_animating = true;
      update(["loading_animation"]);

      final all_posts = await post_service.get_all_posts();

      // 加载完成后播放动画
      is_animating = false;
      update(["loading_animation"]);
      play_pulse_animation();

      // Limit to only 3 posts
      return all_posts.take(3).toList();
    } catch (e) {
      print('Error loading posts: $e');
      is_animating = false;
      update(["loading_animation"]);
      play_shake_animation();
      return [];
    }
  }
}
